import frappe
from functools import wraps
import json
import requests
from datetime import datetime

def check_token(func):
    """装饰器：检测Token是否存在，不存在则自动刷新"""
    @wraps(func)  # 保留原函数元信息
    def wrapper(*args, **kwargs):
        # 1. 定义缓存中的Token键名
        token_key = "book_token"
        
        # 2. 尝试获取缓存中的Token
        token = frappe.cache().get_value(token_key)
        
        # 3. 如果Token不存在或已过期
        if not token:
            # 调用刷新Token的函数（需自定义实现）
            new_token = get_token()
            
            # 将新Token存入缓存（假设有效期3600秒）
            frappe.cache().set_value(
                token_key,
                new_token,
                expires_in_seconds=3600
            )
            frappe.logger().info("Token refreshed via decorator")
        
        # 4. 执行原方法
        return func(*args, **kwargs)
    return wrapper

def get_book_token():
    wxwork_token = frappe.cache().get("wxwork_token")
    if not wxwork_token:
        wxwork_setting = frappe.get_doc('wxwork_setting')
        # print('1111111111111')
        # print(wxwork_setting.corpid)
        # print(wxwork_setting.get_password('app_secret'))        
        kw = {'corpid':wxwork_setting.corpid,'corpsecret':wxwork_setting.get_password('app_secret')} 
        response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?", params = kw)
        token_result = response.json()
        print(token_result)
        if token_result['errcode'] == 0 :
            wxwork_token = token_result['access_token']
            expire_seconds = token_result['expires_in']            
            frappe.cache().set(name="wxwork_token", value=wxwork_token, ex=expire_seconds-1200)
    return wxwork_token 

def get_app_token():
    wxwork_token = frappe.cache().get("wxwork_token")
    if not wxwork_token:
        wxwork_setting = frappe.get_doc('wxwork_setting')
        # print('1111111111111')
        # print(wxwork_setting.corpid)
        # print(wxwork_setting.get_password('app_secret'))        
        kw = {'corpid':wxwork_setting.corpid,'corpsecret':wxwork_setting.get_password('app_secret')} 
        response = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?", params = kw)
        token_result = response.json()
        print(token_result)
        if token_result['errcode'] == 0 :
            wxwork_token = token_result['access_token']
            expire_seconds = token_result['expires_in']            
            frappe.cache().set(name="wxwork_token", value=wxwork_token, ex=expire_seconds-1200)
    return wxwork_token 